﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Reflection;

namespace XComplica.SharePoint
{
    public class MetaFilteredField : SPFieldLookup
    {
        public MetaFilteredField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        { }

        public MetaFilteredField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        { }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                MetaFilteredFieldControl fieldControl = new MetaFilteredFieldControl();
                fieldControl.FieldName = InternalName;
                fieldControl.AllowMultipleValues = this.AllowMultipleValues;
                return fieldControl;         
            }
        }

        public override bool AllowMultipleValues
        {
            get
            {
                return base.AllowMultipleValues;
            }
            set
            {
                base.AllowMultipleValues = value;
                // without this line, SharePoint resets our field back to the basic lookup field when switching from multi to single. 
                this.SetFieldAttribute("Type", "MetaFilteredLookup");

            }
        }

        private void SetFieldAttribute(string attribute, string value)
        {
            //Hack: Invokes an internal method from the base class
            Type baseType = typeof(MetaFilteredField);
            MethodInfo mi = baseType.GetMethod("SetFieldAttributeValue", BindingFlags.Instance | BindingFlags.NonPublic);
            mi.Invoke(this, new object[] { attribute, value });
        }

        private string GetFieldAttribute(string attribute)
        {
            //Hack: Invokes an internal method from the base class
            Type baseType = typeof(MetaFilteredField);
            MethodInfo mi = baseType.GetMethod("GetFieldAttributeValue", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);
            object obj = mi.Invoke(this, new object[] { attribute });

            if (obj == null)
                return "";
            else
                return obj.ToString();

        }
    }
}
